#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <X11/Xlib.h>
#include <tinywidgets/tnWidgets.h>
#include <X11/keysymdef.h>
#include "util.h"
#include "intfMsg.h"

static int msqid_dest;
const static int keymap [] = {
    0x42, XK_1,
    0x43, XK_2,
    0x0f, XK_3,
    0x1e, XK_4,
    0x1d, XK_5,
    0x1c, XK_6,
    0x18, XK_7,
    0x16, XK_8,
    0x17, XK_9,
    0x12, XK_0,

    0x57, XK_Prior,
    0x4d, XK_Next,
    0x55, XK_Pause,
    0x1a, XK_End,
    0x4f, XK_AudioRaiseVolume,
    0x48, XK_AudioLowerVolume,

    -1, -1
};


static void send_keypress(unsigned int key)
{
    int xkey = -1;
    printf("key: %x\n", key);
    for (int i=0; keymap[i] != -1; i+=2) {
        if (key == keymap[i]) {
            xkey = keymap[i + 1];
            break;
        }
    }
    printf("xkey: %x\n", xkey);
 
    RtnMsg msg;
    msg.msg_code = MSG_MAIN_IR_KEYCODE;
    msg.msg_len = sizeof(xkey);
    memcpy(msg.msg_data, &xkey, sizeof(xkey));
    SendMessage(msqid_dest, &msg);
}


int main(int argc, char ** argv)
{
    msqid_dest      = OpenMsgQueue(KEY_FOR_PLAYER_MESSAGE);
    int key = strtol(argv[1], NULL, 16);
    send_keypress(key);
    return 0;
}

